package com.yzdmw.toutiao.login.ui;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;

import com.yzdmw.toutiao.R;
import com.yzdmw.toutiao.databinding.RegistFragmentBinding;

import org.jetbrains.annotations.NotNull;

public class RegistFragment extends Fragment {

    public static final String TAG = "RegistFragment";
    private LoginViewModel loginViewModel;
    private RegistFragmentBinding binding;

    public static RegistFragment newInstance() {
        return new RegistFragment();
    }

    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = RegistFragmentBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        NavController navController = NavHostFragment.findNavController(this);
        loginViewModel = new ViewModelProvider(navController.getViewModelStoreOwner(R.id.login_nav))
                .get(LoginViewModel.class);

        final EditText usernameEditText = binding.username;
        final EditText passwordEditText = binding.password;
        final EditText confirmPasswordEditText = binding.confirmPassword;
        final Button registButton = binding.regist;
        final ProgressBar loadingProgressBar = binding.loading;

        loginViewModel.getLoginFormState().observe(getViewLifecycleOwner(), loginFormState -> {
            if (loginFormState == null) {
                return;
            }
            registButton.setEnabled(loginFormState.isDataValid());
            if (loginFormState.getUsernameError() != null)
                usernameEditText.setError(getString(loginFormState.getUsernameError()));
            else
                usernameEditText.setError(null);
            if (loginFormState.getPasswordError() != null)
                passwordEditText.setError(getString(loginFormState.getPasswordError()));
            else
                passwordEditText.setError(null);
        });

        loginViewModel.getLoginResult().observe(getViewLifecycleOwner(), loginResult -> {
            if (loginResult == null) {
                return;
            }
            loadingProgressBar.setVisibility(View.GONE);
            if (loginResult.getError() != null) {
                showRegistFailed(loginResult.getError());
            } else {
                registSuccess();
            }
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override public void afterTextChanged(Editable s) {
                loginViewModel.registDataChanged(
                        usernameEditText.getText().toString(),
                        passwordEditText.getText().toString(),
                        confirmPasswordEditText.getText().toString()
                        );
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        confirmPasswordEditText.addTextChangedListener(afterTextChangedListener);

        registButton.setOnClickListener(v -> {
            loadingProgressBar.setVisibility(View.VISIBLE);
            loginViewModel.regist(usernameEditText.getText().toString(),
                    passwordEditText.getText().toString());
        });

    }

    private void showRegistFailed(@StringRes Integer errorString) {
        Toast.makeText(getContext(), errorString, Toast.LENGTH_SHORT).show();
    }

    private void registSuccess() {
        String welcome = getString(R.string.welcome);
        // TODO : navigate to index
        Toast.makeText(getContext(), TAG+welcome, Toast.LENGTH_LONG).show();
    }
}
